import { useEffect } from "react";
import { HashRouter, Route, Routes } from "react-router-dom";
import Web3 from "web3";
import tokenJson from "../build/MyToken.json";
import exchangeJson from "../build/Exchange.json";
import { loadBalanceData } from "../redux/slice/balanceSlice";
import { useDispatch } from "react-redux";
import Dashborad from "./dashborad/index";
import Owner from "./owner";
import NoMatch from "./nomatch";
import App from "../App";

function Content() {
  const dispatch = useDispatch();
  useEffect(() => {
    async function start() {
      // 1.获取连接后的合约
      const web = await initWeb();
      window.web = web; // 挂载到全局对象管理
      // 2.获取资产信息
      dispatch(loadBalanceData(web));
      // 3.获取订单信息

      // 4.事件订阅（如何优化，本地处理list）
      // web.exchangeContract.events.Order({}, (error, event) => {
      //   console.log(event);
      // });+
      
    }
    start();
  }, [dispatch]);
  async function initWeb() {
    // 初始化web3实例
    const web3 = new Web3(Web3.givenProvider || "ws://localhost:8545");
    // 账号授权
    const account = await web3.eth.requestAccounts();
    console.log("授权账号为=>" + account[0]);
    // 连接智能合约
    const networkId = await web3.eth.net.getId();
    const tokenAbi = tokenJson.abi;
    const tokenAddr = tokenJson.networks[networkId].address;
    const tokenContract = await new web3.eth.Contract(tokenAbi, tokenAddr);

    const exchangeAbi = exchangeJson.abi;
    const exchangeAddr = exchangeJson.networks[networkId].address;
    const exchangeContract = await new web3.eth.Contract(
      exchangeAbi,
      exchangeAddr
    );
    return { web3, account: account[0], tokenContract, exchangeContract };
  }
  return (
    <HashRouter>
      <App>
        <Routes>
          <Route path="/" exact element={<Dashborad />} />
          <Route path="/owner" element={<Owner />} />
          <Route path="*" element={<NoMatch />} />
        </Routes>
      </App>
    </HashRouter>
  );
}

export default Content;
